#include "iic.h"
#include "24Cxx.h"
#include "delay.h"
#include <stdio.h>

static u8 AT24CXX_Check(void){//读取最后一个字节
  u8 temp;
  temp=AT24CXX_ReadOneByte(1);
  
  if(temp==0XAA){
	  return 0;
  }	  
  else{
    AT24CXX_WriteOneByte(AT24C08,0XAA);
    temp=AT24CXX_ReadOneByte(AT24C08);	
   
    if(temp==0XAA){
		return 0;
	}
    if(temp!=0xAA){
		return 1;
	}
  }
  return 1;											  
}

void AT24CXX_Init(void){

	IIC_Init_MN();
	while(AT24CXX_Check()){
		printf("EEPROM init error!\n");
		Delay_ms(1000);
	}
}

u8 AT24CXX_ReadOneByte(u16 ReadAddr){				  
	u8 temp=0;		  	    																 
	IIC_Start();  
	if(EE_TYPE>AT24C16){
	IIC_Send_Byte(0XA0);
	IIC_Wait_Ack();
	IIC_Send_Byte(ReadAddr>>8);
	}
	else IIC_Send_Byte(0XA0+((ReadAddr/256)<<1));   
	IIC_Wait_Ack(); 
	IIC_Send_Byte(ReadAddr%256);
	IIC_Wait_Ack();	    
	IIC_Start();  	 	   
	IIC_Send_Byte(0XA1);	   
	IIC_Wait_Ack();	 
	temp=IIC_Read_Byte(0);		   
	IIC_Stop();
  
  return temp;

}

void AT24CXX_WriteOneByte(u16 WriteAddr,u8 DataToWrite){				   	  	    																 
	IIC_Start();  
	if(EE_TYPE>AT24C16){
		IIC_Send_Byte(0XA0);
		IIC_Wait_Ack();
		IIC_Send_Byte(WriteAddr>>8);
	}
	else 
		IIC_Send_Byte(0XA0+((WriteAddr/256)<<1));
	IIC_Wait_Ack();	   
	IIC_Send_Byte(WriteAddr%256);
	IIC_Wait_Ack(); 	 										  		   
	IIC_Send_Byte(DataToWrite);					   
	IIC_Wait_Ack();  		    	   
	IIC_Stop();
	Delay_ms(2);	 
}

void AT24CXX_Read(u16 ReadAddr,u8 *pBuffer,u16 NumToRead){
  while(NumToRead){
    *pBuffer++=AT24CXX_ReadOneByte(ReadAddr++);	
    NumToRead--;
  }
}  

void AT24CXX_Write(u16 WriteAddr,u8 *pBuffer,u16 NumToWrite){
  while(NumToWrite--){
    AT24CXX_WriteOneByte(WriteAddr,*pBuffer);
    WriteAddr++;
    pBuffer++;
  }
}
